package org.argus.job.server.gateway.core.config;

import org.argus.common.redis.service.RedisService;
import org.argus.job.server.gateway.core.loadbalancer.AppNameHeaderLoadBalancer;
import org.argus.job.server.gateway.core.loadbalancer.AppNameServiceInstanceSelector;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * @Author 刘文/Cliff Liu
 * @Date 2024/9/16
 */
public class JobServerLoadBalancingConfiguration {

//    @Bean
//    public AppNameServiceInstanceSelector appNameServiceInstanceSelector(RedisService redisService) {
//        return new AppNameServiceInstanceSelector(redisService);
//    }

    @Bean
    @ConditionalOnMissingBean
    public ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(Environment environment,
        LoadBalancerClientFactory loadBalancerClientFactory,
        AppNameServiceInstanceSelector appNameServiceInstanceSelector) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new AppNameHeaderLoadBalancer(
            loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name,
            appNameServiceInstanceSelector);
    }
}
